import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'dart:ui';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_is_know_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/new_terminal/bg_music/bean/bg_terminal_music_list_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/bg_music/bg_sys_recommend_music_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/select_smart_home_bgm_event.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/set_smart_home_folder_bgm_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_column_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_is_know_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_image_set_category_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_image_set_column_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_image_set_style_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_service.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_set_image_cover_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_store_details_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:keyboard_utils/keyboard_listener.dart';
import 'package:keyboard_utils/keyboard_utils.dart';
import 'package:matisse_android_plugin/export_matisse.dart';
import 'package:photo_preview/photo_preview_export.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart' as prefix;
import 'package:video_thumbnail/video_thumbnail.dart';
import '../../app_main.dart';
import '../smart_home_category_response_bean.dart';
import '../smart_home_style_type_bean.dart';
import '../smart_home_upload_service.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:vg_base/vg_permission_lib.dart';

/// 智能家居打包上传页面
class SmartHomePublishImagePackageUploadPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "SmartHomePublishImagePackageUploadPage";

  final String shid;

  //上传完成后回到的页面
  final String router;
  final String linkUrl;
  final String coverPath;
  final List<SmartHomeUploadItemBean> currentList;
  final String sfid;
  final String title;
  final String desc;
  final int coverIndex;
  final MusicListBean musicInfo;
  final List<MusicListBean> musicList;
  final bool isCreate;

  const SmartHomePublishImagePackageUploadPage(
      {Key key,
        this.shid,
        this.router,
        this.linkUrl,
        this.coverPath,
        this.currentList,
        this.sfid,
        this.title,
        this.desc,
        this.coverIndex,
        this.musicInfo,
        this.musicList,
        this.isCreate
      })
      : super(key: key);

  @override
  _SmartHomePublishImagePackageUploadPageState createState() => _SmartHomePublishImagePackageUploadPageState();

  static Future<Map> navigatorPush(
      BuildContext context,
      String shid,
      {String router,
        String linkUrl,
        String coverPath,
        List<SmartHomeUploadItemBean> currentList,
        String sfid,
        String title,
        String desc,
        int coverIndex,
        MusicListBean musicInfo,
        List<MusicListBean> musicList,
        bool isCreate,
      }) {
    return RouterUtils.routeForFutureResult(
        context,
        SmartHomePublishImagePackageUploadPage(
          shid: shid,
          router: router,
          linkUrl: linkUrl,
          coverPath: coverPath,
          currentList: currentList,
          sfid: sfid,
          title: title,
          desc: desc,
          coverIndex: coverIndex,
          musicInfo: musicInfo,
          musicList: musicList,
          isCreate: isCreate,
        ),
        routeName: SmartHomePublishImagePackageUploadPage.ROUTER);
  }
}

class _SmartHomePublishImagePackageUploadPageState extends BaseState<SmartHomePublishImagePackageUploadPage> {
  TextEditingController _titleController;
  TextEditingController _desController;
  SmartHomeViewModel _viewModel;
  int _picCount = 0;

  //包含上传布局的默认数据
  List<SmartHomeUploadItemBean> _allList = List();

  //要上传的数据
  List<SmartHomeUploadItemBean> _uploadList = List();
  List<String> _toDeleteList = List();

  ///自定义默认上传布局，type为-1
  SmartHomeUploadItemBean _defaultItem =
  new SmartHomeUploadItemBean(type: "-1");


  //封面图
  int _coverIndex;

  String _linkUrl;

  ScrollController _scrollController;

  MusicListBean _musicInfo;
  List<MusicListBean> _musicList = List();
  BgSysRecommendMusicViewModel _musicViewModel;
  StreamSubscription _selectBgmStreamSubscription;

  VideoPlayerController _videoHandleController;

  ColumnListBean _packageColumn = new ColumnListBean();
  SpatialTypeListBean _packageCategory = new SpatialTypeListBean();
  SmartHomeStyleTypeBean _packageStyle = new SmartHomeStyleTypeBean("", "");


  //栏目
  final List<ColumnListBean> _columnList = List();
  //空间
  final List<SpatialTypeListBean> _categoryList = List();
  //风格
  final List<SmartHomeStyleTypeBean> _styleList = List();

  SmartHomePublishViewModel _publishViewModel;

  double _imgContainerWidth = 0;
  double _imgContainerHeight = 0;
  KeyboardUtils _keyboardUtils = KeyboardUtils();
  @override
  void initState() {
    _keyboardUtils.add(listener: KeyboardListener(
        willHideKeyboard: (){
          FocusManager.instance.primaryFocus?.unfocus();
        },
        willShowKeyboard: (height){}
    ));
    super.initState();
    _publishViewModel = new SmartHomePublishViewModel(this);
    _musicInfo = widget?.musicInfo;
    if(widget?.musicList != null){
      _musicList.addAll(widget?.musicList);
    }
    _musicViewModel = new BgSysRecommendMusicViewModel(this, "");
    _scrollController = new ScrollController();

    _titleController = TextEditingController(text: widget?.title ?? "");
    _desController = TextEditingController(text: widget?.desc ?? "");
    _viewModel = SmartHomeViewModel(this);
    if (widget?.currentList != null && widget.currentList.isNotEmpty) {
      _coverIndex = widget?.coverIndex ?? 0;
      _uploadList.addAll(widget?.currentList);
      if (_uploadList.length < 35) {
        _allList.clear();
        _allList.addAll(_uploadList);
        _allList.add(_defaultItem);
      } else {
        _allList.clear();
        _allList.addAll(_uploadList);
      }
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        Future.delayed(Duration(milliseconds: 100), () {
          _scrollController.jumpTo(_scrollController?.position?.maxScrollExtent);
        });
      });
    } else {
      _allList.add(_defaultItem);
    }

    _picCount = _uploadList.length;
    _musicViewModel.musicListValueNotifier.addListener(() {
      if(_musicViewModel.musicListValueNotifier.value != null){
        _musicList.addAll(_musicViewModel.musicListValueNotifier.value);
        int index = Random().nextInt(_musicList.length);
        WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
          setState(() {
            _musicInfo = _musicList.elementAt(index);
          });
        });
      }
    });
    _musicViewModel.getBgByHsnWithoutCallback(context, "");
    _selectBgmStreamSubscription =
        VgEventBus.global.on<SelectSmartHomeBgmEvent>()?.listen((event) {
          if(event.musicListBean == null && event.cancelUse){
            setState(() {
              _musicInfo = null;
            });
          }
        });
    setPackageInfo();
  }

  //设置整体设置的数据
  void setPackageInfo(){
    if((_uploadList?.length??0) < 1){
      return;
    }
    bool columnSame = true;
    bool categorySame = true;
    bool styleSame = true;
    String columnName = _uploadList?.elementAt(0)?.scidName;
    String categoryName = _uploadList?.elementAt(0)?.stidName;
    String styleName = _uploadList?.elementAt(0)?.styleName;
    _uploadList.forEach((element) {
      if(StringUtils.isNotEmpty(element?.scidName) && columnName != element?.scidName){
        columnSame = false;
      }
      if(StringUtils.isNotEmpty(element?.stidName) && categoryName != element?.stidName){
        categorySame = false;
      }
      if(StringUtils.isNotEmpty(element?.styleName) && styleName != element?.styleName){
        styleSame = false;
      }
    });
    if(columnSame){
      _packageColumn?.name = columnName;
      _packageColumn?.scid = _uploadList?.elementAt(0)?.scid;
    }
    if(categorySame){
      _packageCategory?.name = categoryName;
      _packageCategory?.stid = _uploadList?.elementAt(0)?.stid;
    }
    if(styleSame){
      _packageStyle?.name = styleName;
      _packageStyle?.style = _uploadList?.elementAt(0)?.style;
    }
  }

  @override
  void dispose() {
    _titleController?.clear();
    _titleController?.dispose();
    _desController?.clear();
    _desController?.dispose();
    _selectBgmStreamSubscription?.cancel();
    _videoHandleController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
        child: WillPopScope(
          onWillPop: _withdrawFront,
          child: Scaffold(
            resizeToAvoidBottomInset: false,
            resizeToAvoidBottomPadding: false,
            backgroundColor: Colors.white,
            body: _toMainColumnWidget(),
          ),
        ));
  }

  Widget _toMainColumnWidget() {
    return CommonPackUpKeyboardWidget(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _toTopBarWidget(),
          Container(
            height: 10,
            color: Color(0XFFF6F7F9),
          ),
          _toSmartHomeTitleWidget(),
          Container(
            margin: EdgeInsets.only(left: 15),
            height: 1,
            color: Color(0XFFEEEEEE),
          ),
          _toDesWidget(),
          _toDesTextLengthWidget(),
          Container(
            height: 10,
            color: Color(0XFFF6F7F9),
          ),
          _toPackageSettingWidget(),
          _toGridPage(),
          _toSelectBgmWidget(),
        ],
      ),
    );
  }

  ///页面标题
  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      isShowBack: true,
      backgroundColor: Color(0XFFF6F7F9),
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      backRightWidget: _toTitleWidget(),
      isShowBackRightWdiget: true,
      rightWidget: _toSaveWidget(),
      navFunction: (){
        onBackPressed();
      },
    );
  }

  Widget _toTitleWidget(){
    return Text(
      StringUtils.isNotEmpty(widget?.sfid)?"编辑":"打包上传",
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
      style: TextStyle(
          color: ThemeRepository.getInstance().getCardBgColor_21263C(),
          fontSize: 17,
          height: 1.22,
          fontWeight: FontWeight.w600),
    );
  }

  void onBackPressed()async{
    if(_uploadList.length < 1 && StringUtils.isEmpty(_getTitle()) && StringUtils.isEmpty(_getDesc())){
      //直接返回
      RouterUtils.pop(context);
      return;
    }
    FocusScope.of(context).requestFocus(FocusNode());
    bool result =
    await CommonConfirmCancelDialog.navigatorPushDialog(context,
      title: "提示",
      content: "退出后将不会保存您的内容，确认退出？",
      cancelText: "取消",
      confirmText: "退出",
      confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      cancelBgColor: Color(0xFFF6F7F9),
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      widgetBgColor: Colors.white,
    );
    //去裁剪
    if(result??false){
      RouterUtils.pop(context);
    }
    return;
  }

  Future<bool> _withdrawFront() async {
    if(_uploadList.length < 1 && StringUtils.isEmpty(_getTitle()) && StringUtils.isEmpty(_getDesc())){
      //直接返回
      return true;
    }
    FocusScope.of(context).requestFocus(FocusNode());
    bool result =
    await CommonConfirmCancelDialog.navigatorPushDialog(context,
      title: "提示",
      content: "退出后将不会保存您的内容，确认退出？",
      cancelText: "取消",
      confirmText: "退出",
      confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      cancelBgColor: Color(0xFFF6F7F9),
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      widgetBgColor: Colors.white,
    );
    if(result??false){
      return true;
    }
    return false;
  }

  Widget _toSaveWidget() {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        if(StringUtils.isEmpty(_getTitle()) && StringUtils.isEmpty(_getDesc())){
          VgToastUtils.toast(context, "请输入标题或描述");
          return;
        }
        if(_uploadList.length < 1){
          return;
        }
        _upload();
      },
      child: Container(
        width: 48,
        height: 24,
        decoration: BoxDecoration(
          color: (_uploadList.length > 0 && (StringUtils.isNotEmpty(_getTitle()) || StringUtils.isNotEmpty(_getDesc())))?ThemeRepository.getInstance().getPrimaryColor_1890FF():Color(0xFFCFD4DB),
          borderRadius: BorderRadius.circular(12),
        ),
        alignment: Alignment.center,
        child: Text(
          "发布",
          style: TextStyle(
              color: Colors.white, fontSize: 12, fontWeight: FontWeight.w500),
        ),
      ),
    );
  }

  void _upload() {
    // if(_uploadList?.length == 1 && StringUtils.isNotEmpty(_uploadList[0]?.netUrl) && PhotoPreviewToolUtils.isNetUrl(_uploadList[0]?.netUrl)){
    //   //编辑图片，无需上传
    //   SmartHomeUploadItemBean itemBean = _uploadList[0];
    //   _viewModel.editImage(context, widget?.shid, itemBean?.picid, itemBean?.backup, itemBean?.stid, itemBean?.style, widget?.router);
    //   return;
    // }
    String deleteIds = "";
    _toDeleteList.forEach((element) {
      deleteIds += element;
      deleteIds += ",";
    });
    SmartHomePublishService service = SmartHomePublishService().setList(
      context,
      widget?.shid,
      "",
      _getTitle(),
      _getDesc(),
      _uploadList,
      _coverIndex ?? 0,
      widget?.sfid ?? "",
      _musicInfo?.id??"",
      deleteIds: deleteIds,
    );
    if (service != null) {
      VgHudUtils.show(context, "正在发布");
      if ((_uploadList?.length ?? 0) > 0) {
        //多图上传
        service.packageUpload(VgBaseCallback(onSuccess: (val) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, "上传完成");
          RouterUtils.popUntil(
              context, widget?.router ?? SmartHomeStoreDetailsPage.ROUTER);
        }, onError: (msg) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, "上传失败");
          RouterUtils.popUntil(
              context, widget?.router ?? SmartHomeStoreDetailsPage.ROUTER);
        }));
      }
    }
  }

  String _getDesc(){
    String desc = _desController.text.trim();
    if(desc.length > 200){
      desc = desc.substring(0, 200);
    }
    return desc;
  }

  String _getTitle(){
    String title = _titleController.text.trim();
    if(title.length > 30){
      title = title.substring(0, 30);
    }
    return title;
  }


  ///标题
  Widget _toSmartHomeTitleWidget() {
    Color color = Color(0XFFB0B3BF);
    if((_titleController?.text?.length??0) > 0){
      if((_titleController?.text?.length??0) <= 30){
        color = ThemeRepository.getInstance().getPrimaryColor_1890FF();
      }else{
        color = Color(0XFFF95355);
      }
    }
    return Container(
      color: Colors.white,
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.only(left: 15, right: 10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Expanded(
            child: Container(
              constraints: BoxConstraints(
                  minHeight: 50,
                  maxHeight: 100
              ),
              child: VgTextField(
                controller: _titleController,
                keyboardType: TextInputType.text,
                autofocus: (widget?.isCreate??true),
                textAlign: TextAlign.left,
                style: TextStyle(
                    color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                    fontWeight: FontWeight.w600,
                    fontSize: 14),
                decoration: new InputDecoration(
                    counterText: "",
                    hintText: "写个标题，便于管理，也能提高用户点击率～",
                    border: InputBorder.none,
                    hintStyle: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Color(0XFFB0B3BF))),
                maxLines: 2,
                minLines: 1,
                maxLimitLength: Platform.isAndroid ? 30 : null,
                zhCountEqEnCount: true,
                limitCallback: (int) {
                  Platform.isAndroid
                      ? VgToastUtils.toast(context, "最多可输入${30}个字")
                      : {};
                },
                onChanged: (value) {
                  setState(() { });
                  // _notifyChange();
                },
              ),
            ),
          ),
          SizedBox(width: 15,),
          Text(
            "${_titleController?.text?.length??0}",
            style: TextStyle(
              fontSize: 10,
              color: color,
            ),
          ),
          Text(
            "/",
            style: TextStyle(
                fontSize: 10,
                color: Color(0XFFB0B3BF)
            ),
          ),
          Text(
            "30",
            style: TextStyle(
                fontSize: 10,
                color: Color(0XFFB0B3BF)
            ),
          ),
        ],
      ),
    );
  }

  ///详细描述
  Widget _toDesWidget() {
    return Container(
      height: 100,
      color: Colors.white,
      padding: EdgeInsets.symmetric(horizontal: 15),
      alignment: Alignment.topLeft,
      child: Container(
        height: 100,
        child: VgTextField(
          controller: _desController,
          keyboardType: TextInputType.text,
          autofocus: false,
          textAlign: TextAlign.left,
          style: TextStyle(
              color: ThemeRepository.getInstance().getCardBgColor_21263C(),
              fontSize: 14),
          decoration: new InputDecoration(
              counterText: "",
              hintText: "可输入详细描述",
              border: InputBorder.none,
              hintStyle: TextStyle(fontSize: 14, color: Color(0XFFB0B3BF))),
          maxLimitLength: Platform.isAndroid ? 200 : null,
          zhCountEqEnCount: true,
          limitCallback: (int) {
            Platform.isAndroid
                ? VgToastUtils.toast(context, "最多可输入${200}个字")
                : {};
          },
          onChanged: (value) {
            // _notifyChange();
            setState(() { });
          },
        ),
      ),
    );
  }

  ///字数提示
  Widget _toDesTextLengthWidget(){
    Color color = Color(0XFFB0B3BF);
    if((_desController?.text?.length??0) > 0){
      if((_desController?.text?.length??0) <= 200){
        color = ThemeRepository.getInstance().getPrimaryColor_1890FF();
      }else{
        color = Color(0XFFF95355);
      }
    }
    return Container(
      height: 20,
      padding: EdgeInsets.only(right: 10),
      alignment: Alignment.centerRight,
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            "${_desController?.text?.length??0}",
            style: TextStyle(
              fontSize: 10,
              color: color,
            ),
          ),
          Text(
            "/",
            style: TextStyle(
                fontSize: 10,
                color: Color(0XFFB0B3BF)
            ),
          ),
          Text(
            "200",
            style: TextStyle(
                fontSize: 10,
                color: Color(0XFFB0B3BF)
            ),
          ),
        ],
      ),
    );
  }

  ///整体设置
  Widget _toPackageSettingWidget(){
    return Container(
      height: 50,
      color: Colors.white,
      padding: EdgeInsets.only(left:10, right: 12),
      alignment: Alignment.centerLeft,
      child: Row(
        children: [
          Container(
            width: 65,
            alignment: Alignment.center,
            child: Text(
              "整体设置：",
              style: TextStyle(
                fontSize: 13,
                color: Color(0XFF5E687C),
              ),
            ),
          ),
          Container(
            width: ScreenUtils.screenW(context) - 87,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                _toSelectColumnWidget(),
                _toSelectCategoryWidget(),
                _toSelectStyleWidget(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  ///选择类别
  Widget _toSelectColumnWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if(_columnList.isNotEmpty){
          SmartHomePublishImageSetColumnDialog.navigatorPushDialog(context,
              _packageColumn?.scid,
              _columnList, (columnListBean){
                setState(() {
                  _packageColumn?.scid = columnListBean?.scid;
                  _packageColumn?.name = columnListBean?.name;
                  setItemColumnByPackageColumn();
                });
              });
        }else{
          _publishViewModel.getLatestColumn(widget?.shid, (columnList){
            _columnList.addAll(columnList);
            SmartHomePublishImageSetColumnDialog.navigatorPushDialog(context,
                _packageColumn?.scid,
                _columnList, (columnListBean){
                  setState(() {
                    _packageColumn?.scid = columnListBean?.scid;
                    _packageColumn?.name = columnListBean?.name;
                    setItemColumnByPackageColumn();
                  });
                });
          });
        }

      },
      child: Container(
        height: 26,
        width: 83,
        padding: EdgeInsets.symmetric(horizontal: 8),
        alignment: Alignment.center,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              StringUtils.isNotEmpty(_packageColumn?.name)?_packageColumn?.name:"类别",
              style: TextStyle(
                  fontSize: 13,
                  color: StringUtils.isNotEmpty(_packageColumn?.name)?ThemeRepository.getInstance().getCardBgColor_21263C():Color(0XFFB0B3BF)
              ),
            ),
            SizedBox(width: 4,),
            Image.asset(
              "images/icon_arrow_down_black.png",
              width: 6,
            )
          ],
        ),
      ),
    );
  }

  ///子item设置为整体设置的属性
  void setItemColumnByPackageColumn(){
    _uploadList.forEach((element) {
      element.scid = _packageColumn.scid;
      element.scidName = _packageColumn.name;
    });
  }

  ///选择空间
  Widget _toSelectCategoryWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if(_categoryList.isNotEmpty){
          SmartHomePublishImageSetCategoryDialog.navigatorPushDialog(context,
              _packageCategory?.stid,
              _categoryList, (categoryListBean){
                setState(() {
                  _packageCategory?.stid = categoryListBean?.stid;
                  _packageCategory?.name = categoryListBean?.name;
                  setItemCategoryByPackageColumn();
                });
              });
        }else{
          _publishViewModel.getLatestCategory(widget?.shid, (categoryList){
            _categoryList.addAll(categoryList);
            SmartHomePublishImageSetCategoryDialog.navigatorPushDialog(context,
                _packageCategory?.stid,
                _categoryList, (categoryListBean){
                  setState(() {
                    _packageCategory?.stid = categoryListBean?.stid;
                    _packageCategory?.name = categoryListBean?.name;
                    setItemCategoryByPackageColumn();
                  });
                });
          });
        }
      },
      child: Container(
        height: 26,
        width: 83,
        padding: EdgeInsets.symmetric(horizontal: 8),
        alignment: Alignment.center,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              StringUtils.isNotEmpty(_packageCategory?.name)?_packageCategory?.name:"空间",
              style: TextStyle(
                  fontSize: 13,
                  color: StringUtils.isNotEmpty(_packageCategory?.name)?ThemeRepository.getInstance().getCardBgColor_21263C():Color(0XFFB0B3BF)
              ),
            ),
            SizedBox(width: 4,),
            Image.asset(
              "images/icon_arrow_down_black.png",
              width: 6,
            )
          ],
        ),
      ),
    );
  }

  ///子item设置为整体设置的属性
  void setItemCategoryByPackageColumn(){
    _uploadList.forEach((element) {
      element.stid = _packageCategory.stid;
      element.stidName = _packageCategory.name;
    });
  }

  ///选择风格
  Widget _toSelectStyleWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if(_styleList.isNotEmpty){
          SmartHomePublishImageSetStyleDialog.navigatorPushDialog(context,
              _packageStyle?.style,
              _styleList, (styleBean){
                setState(() {
                  _packageStyle?.style = styleBean?.style;
                  _packageStyle?.name = styleBean?.name;
                  setItemStyleByPackageColumn();
                });
              });
        }else{
          _publishViewModel.getLatestStyle(widget?.shid, (styleList){
            _styleList.addAll(styleList);
            SmartHomePublishImageSetStyleDialog.navigatorPushDialog(context,
                _packageStyle?.style,
                _styleList, (styleBean){
                  setState(() {
                    _packageStyle?.style = styleBean?.style;
                    _packageStyle?.name = styleBean?.name;
                    setItemStyleByPackageColumn();
                  });
                });
          });
        }

      },
      child: Container(
        height: 26,
        width: 83,
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(horizontal: 8),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              StringUtils.isNotEmpty(_packageStyle?.name)?_packageStyle?.name:"风格",
              style: TextStyle(
                  fontSize: 13,
                  color: StringUtils.isNotEmpty(_packageStyle?.name)?ThemeRepository.getInstance().getCardBgColor_21263C():Color(0XFFB0B3BF)
              ),
            ),
            SizedBox(width: 4,),
            Image.asset(
              "images/icon_arrow_down_black.png",
              width: 6,
            )
          ],
        ),
      ),
    );
  }

  ///子item设置为整体设置的属性
  void setItemStyleByPackageColumn(){
    _uploadList.forEach((element) {
      element.style = _packageStyle.style;
      element.styleName = _packageStyle.name;
    });
  }

  ///图片列表
  Widget _toGridPage(){
    return Expanded(
      child: GridView.builder(
        padding: EdgeInsets.only(
            left: 10,
            right: 10,
            bottom: getNavHeightDistance(context)
        ),
        itemCount: _allList.length ?? 0,
        physics: BouncingScrollPhysics(),
        shrinkWrap: true,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          mainAxisSpacing: 8,
          crossAxisSpacing: 7,
          childAspectRatio: 174 / 214,
        ),
        itemBuilder: (BuildContext context, int index) {
          return _toGridItemWidget(context, index, _allList?.elementAt(index));
        },
        controller: _scrollController,
      ),
    );
  }

  Widget _toGridItemWidget(BuildContext context, int index, SmartHomeUploadItemBean itemBean){
    _imgContainerWidth = (ScreenUtils.screenW(context) - 20 - 7)/2;
    _imgContainerHeight = (_imgContainerWidth * 214)/174;
    if (itemBean?.isDefault() ?? false) {
      return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: throttle(() async {
          _selectImage();
          await Future.delayed(Duration(milliseconds: 2000));
        }),
        child: Container(
          width: _imgContainerWidth,
          height: _imgContainerHeight,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4), color: Color(0XFFF6F7F9)),
          alignment: Alignment.center,
          child: Image.asset(
            "images/icon_smart_home_add_img.png",
            width: 80,
          ),
        ),
      );
    }
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){

      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: Column(
          children: [
            Container(
              height: _imgContainerWidth,
              width: _imgContainerWidth,
              child: Stack(
                children: [
                  Container(
                    height: _imgContainerWidth,
                    width: _imgContainerWidth,
                    color: Color(0XFFF2F3F4),
                    child: VgCacheNetWorkImage(
                      itemBean?.getLocalPicUrl() ?? "",
                      fit: BoxFit.cover,
                      imageQualityType: ImageQualityType.high,),
                  ),
                  Visibility(
                    visible: _uploadList.length > 1 &&
                        _coverIndex != null &&
                        (_uploadList?.elementAt(_coverIndex)?.getLocalPicUrl() ==
                            (itemBean?.getLocalPicUrl() ?? "")),
                    child: Positioned(
                      top: 6,
                      left: 6.5,
                      child: Container(
                        height: 13,
                        width: 26,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(1),
                            color: Color(0XFFFFB714)),
                        child: Text(
                          "封面",
                          style: TextStyle(
                            fontSize: 9,
                            color:
                            ThemeRepository.getInstance().getCardBgColor_21263C(),
                          ),
                        ),
                      ),
                    ),
                  ),
                  Visibility(
                    visible: _uploadList.length > 1 && index == 0,
                    child: Align(
                      alignment: Alignment.bottomCenter,
                      child: _toSetCoverWidget(),
                    ),
                  ),
                  Positioned(
                    top: 0,
                    right: 0,
                    child: _toDeleteWidget(itemBean),
                  ),
                ],
              ),
            ),
            Container(
              height: _imgContainerHeight - _imgContainerWidth,
              alignment: Alignment.center,
              color: Color(0XFFF2F3F4),
              child: Row(
                children: [
                  _toSetSingleColumnWidget(_imgContainerWidth, index, itemBean),
                  _toSetSingleCategoryWidget(_imgContainerWidth, index, itemBean),
                  _toSetSingleStyleWidget(_imgContainerWidth, index, itemBean),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _toSetCoverWidget({double width}){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () async {
        int coverIndex =
        await SmartHomePublishSetImageCoverPage.navigatorPush(
            context, _uploadList, _coverIndex);
        if (coverIndex != null) {
          setState(() {
            _coverIndex = coverIndex;
          });
        }
      },
      child: Container(
        height: 40,
        width: width??double.maxFinite,
        alignment: Alignment.center,
        color: Color(0X80000000),
        child: Text(
          "选封面",
          style: TextStyle(
            fontSize: 12,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
      ),
    );
  }

  _toDeleteWidget(SmartHomeUploadItemBean itemBean) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        if(_uploadList.length <= 2){
          SmartHomeISeeDialog.navigatorPushDialog(context, content: "组图动态不得少于2张图片");
          return;
        }
        setState(() {
            if(_coverIndex != null &&
                (_uploadList?.elementAt(_coverIndex)?.getLocalPicUrl() ==
                    (itemBean?.getLocalPicUrl() ?? ""))){
              //当前删除的是封面，
              _coverIndex = 0;
              _uploadList.remove(itemBean);
            }else{
              //当前删除的不是封面
              SmartHomeUploadItemBean covertItem = _uploadList?.elementAt(_coverIndex);
              _uploadList.remove(itemBean);
              _coverIndex = _uploadList.indexOf(covertItem);
            }
            if(StringUtils.isNotEmpty(itemBean.picid)){
              _toDeleteList.add(itemBean.picid);
            }
            //图片
            if (_uploadList.length < 35) {
              _allList.clear();
              _allList.addAll(_uploadList);
              _allList.add(_defaultItem);
            }
          _picCount = _uploadList.length;
        });
      },
      child: Container(
        height: 35,
        width: 35,
        alignment: Alignment.topRight,
        padding: EdgeInsets.only(top: 6, right: 6),
        child: Image.asset(
          "images/icon_smart_home_delete_img.png",
          width: 15,
        ),
      ),
    );
  }

  ///类目
  Widget _toSetSingleColumnWidget(double width, int index, SmartHomeUploadItemBean itemBean){
    return Expanded(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: (){
          if(_columnList.isNotEmpty){
            SmartHomePublishImageSetColumnDialog.navigatorPushDialog(context,
                itemBean?.scid,
                _columnList, (columnListBean){
                  setState(() {
                    itemBean?.scid = columnListBean?.scid;
                    itemBean?.scidName = columnListBean?.name;
                    if(itemBean?.scidName != _packageColumn?.name){
                      _packageColumn?.name = "";
                      _packageColumn?.scid = "";
                    }
                  });
                });
          }else{
            _publishViewModel.getLatestColumn(widget?.shid, (columnList){
              _columnList.addAll(columnList);
              SmartHomePublishImageSetColumnDialog.navigatorPushDialog(context,
                  itemBean?.scid,
                  _columnList, (columnListBean){
                    setState(() {
                      itemBean?.scid = columnListBean?.scid;
                      itemBean?.scidName = columnListBean?.name;
                      if(itemBean?.scidName != _packageColumn?.name){
                        _packageColumn?.name = "";
                        _packageColumn?.scid = "";
                      }
                    });
                  });
            });
          }
        },
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              StringUtils.isNotEmpty(itemBean?.scidName)?itemBean?.scidName:"类别",
              style: TextStyle(
                  fontSize: 12,
                  color: StringUtils.isNotEmpty(itemBean?.scidName)?ThemeRepository.getInstance().getCardBgColor_21263C():Color(0XFF8B93A5)
              ),
            ),
            SizedBox(width: 4,),
            Image.asset(
              "images/icon_arrow_down_black.png",
              width: 6,
            )
          ],
        ),
      ),
    );
  }

  ///空间
  Widget _toSetSingleCategoryWidget(double width, int index, SmartHomeUploadItemBean itemBean){
    return Expanded(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: (){
          if(_categoryList.isNotEmpty){
            SmartHomePublishImageSetCategoryDialog.navigatorPushDialog(context,
                itemBean?.stid,
                _categoryList, (categoryListBean){
                  setState(() {
                    itemBean?.stid = categoryListBean?.stid;
                    itemBean?.stidName = categoryListBean?.name;
                    if(itemBean?.stidName != _packageCategory?.name){
                      _packageCategory?.name = "";
                      _packageCategory?.stid = "";
                    }
                  });
                });
          }else{
            _publishViewModel.getLatestCategory(widget?.shid, (categoryList){
              _categoryList.addAll(categoryList);
              SmartHomePublishImageSetCategoryDialog.navigatorPushDialog(context,
                  itemBean?.stid,
                  _categoryList, (categoryListBean){
                    setState(() {
                      itemBean?.stid = categoryListBean?.stid;
                      itemBean?.stidName = categoryListBean?.name;
                      if(itemBean?.stidName != _packageCategory?.name){
                        _packageCategory?.name = "";
                        _packageCategory?.stid = "";
                      }
                    });
                  });
            });
          }
        },
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              StringUtils.isNotEmpty(itemBean?.stidName)?itemBean?.stidName:"空间",
              style: TextStyle(
                fontSize: 12,
                color: StringUtils.isNotEmpty(itemBean?.stidName)?ThemeRepository.getInstance().getCardBgColor_21263C():Color(0XFF8B93A5),
              ),
            ),
            SizedBox(width: 4,),
            Image.asset(
              "images/icon_arrow_down_black.png",
              width: 6,
            )
          ],
        ),
      ),
    );
  }

  ///选择风格
  Widget _toSetSingleStyleWidget(double width, int index, SmartHomeUploadItemBean itemBean){
    return Expanded(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: (){
          if(_styleList.isNotEmpty){
            SmartHomePublishImageSetStyleDialog.navigatorPushDialog(context,
                itemBean?.style,
                _styleList, (styleBean){
                  setState(() {
                    itemBean?.style = styleBean?.style;
                    itemBean?.styleName = styleBean?.name;
                    if(itemBean?.styleName != _packageStyle?.name){
                      _packageStyle?.name = "";
                      _packageStyle?.style = "";
                    }
                  });
                });
          }else{
            _publishViewModel.getLatestStyle(widget?.shid, (styleList){
              _styleList.addAll(styleList);
              SmartHomePublishImageSetStyleDialog.navigatorPushDialog(context,
                  itemBean?.style,
                  _styleList, (styleBean){
                    setState(() {
                      itemBean?.style = styleBean?.style;
                      itemBean?.styleName = styleBean?.name;
                      if(itemBean?.styleName != _packageStyle?.name){
                        _packageStyle?.name = "";
                        _packageStyle?.style = "";
                      }
                    });
                  });
            });
          }
        },
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              StringUtils.isNotEmpty(itemBean?.getStyleName())?itemBean?.getStyleName():"风格",
              style: TextStyle(
                fontSize: 12,
                color: StringUtils.isNotEmpty(itemBean?.getStyleName())?ThemeRepository.getInstance().getCardBgColor_21263C():Color(0XFF8B93A5),
              ),
            ),
            SizedBox(width: 2,),
            Image.asset(
              "images/icon_arrow_down_black.png",
              width: 6,
            )
          ],
        ),
      ),
    );
  }

  ///选择bgm
  Widget _toSelectBgmWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: ()async{
        if(_musicList.isEmpty){
          _musicViewModel.getBgByHsn(context, "", (musicList) async {
            _musicList.addAll(musicList);
            MusicListBean musicListBean = await SetSmartHomeFolderBgmDialog.navigatorPushDialog(context, _musicList, null, _musicInfo?.id);
            if(musicListBean != null){
              setState(() {
                _musicInfo = musicListBean;
              });
            }

          });
        }else{
          MusicListBean musicListBean = await SetSmartHomeFolderBgmDialog.navigatorPushDialog(context, _musicList, null, _musicInfo?.id);
          if(musicListBean != null){
            setState(() {
              _musicInfo = musicListBean;
            });
          }
        }
      },
      child: Container(
        height: 50 + ScreenUtils.getBottomBarH(context),
        padding: EdgeInsets.only(left: 15, right: 15, bottom: ScreenUtils.getBottomBarH(context)),
        alignment: Alignment.centerLeft,
        decoration: BoxDecoration(
            color: Colors.white,
            boxShadow: [ BoxShadow(
                color: Color(0xff000000).withOpacity(0.06),
                offset: Offset(0, -2),
                blurRadius: 20
            )]
        ),
        child: Row(
          children: [
            Container(
              width: 38,
              height: 38,
              alignment: Alignment.center,
              child: Opacity(
                opacity: (_musicInfo == null)?0.5:1,
                child: Image.asset(
                  "images/icon_smart_home_bgm.png",
                  width: 32,
                  height: 32,
                ),
              ),
            ),
            SizedBox(width: 8,),
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _musicInfo?.mname??"背景音乐",
                    style: TextStyle(
                      fontSize: 15,
                      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                    ),
                  ),
                  Visibility(visible: _musicInfo != null,child: SizedBox(height: 1,)),
                  Visibility(
                      visible: _musicInfo != null,
                      child: Text(
                        _musicInfo?.mtime??"",
                        style: TextStyle(
                            fontSize: 11,
                            color: Color(0XFF8B93A5)
                        ),
                      )
                  ),
                ],
              ),
            ),
            Spacer(),
            Visibility(
                visible: _musicInfo == null,
                child: Text(
                  "去选择",
                  style: TextStyle(
                      fontSize: 12,
                      color: Color(0XFF8B93A5)
                  ),
                )
            ),
            SizedBox(width: 8,),
            Image.asset(
              "images/icon_arrow_right_grey.png",
              width: 6,
              color: Color(0XFF8B93A5),
            ),
          ],
        ),
      ),
    );
  }

  /// 函数节流
  ///
  /// [func]: 要执行的方法
  Function throttle(
      Future Function() func,
      ) {
    if (func == null) {
      return func;
    }
    bool enable = true;
    Function target = () {
      if (enable == true) {
        enable = false;
        func().then((_) {
          enable = true;
        });
      }
    };
    return target;
  }

  void _selectImage() async {
    //图片
    List<String> resultList = await MatisseUtil.selectPhoto(
      context: context,
      maxSize: (35 - (_uploadList?.length??0)),
      maxAutoFinish: false,
      imageRadioMaxLimit: 3,
      imageRadioMinLimit: 0.3,
        onRequestPermission: (msg)async{
          bool result =
          await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: msg,
            cancelText: "取消",
            confirmText: "去授权",
            confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
            cancelBgColor: Color(0xFFF6F7F9),
            titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
            contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
            widgetBgColor: Colors.white,
          );
          if (result ?? false) {
            PermissionUtil.openAppSettings();
          }
        }
    );
    _doHandleData(resultList);
  }

  void _doHandleData(List<String> resultList) {
    if (resultList == null || resultList.isEmpty) {
      return;
    }
    List<SmartHomeUploadItemBean> selectList = List();
    Map<String, ImageInfo> _imageInfoMap = new Map();
    //获取选择的图片或者视频
    String localUrl = resultList[0];
    if (StringUtils.isEmpty(localUrl)) {
      return;
    }
    loading(true, msg: "图片处理中");
    int computeCount = 0;
    resultList.forEach((element) {
      FileImage image = FileImage(File(element));
      image.resolve(new ImageConfiguration()).addListener(
          new ImageStreamListener((ImageInfo info, bool _) async {
            _imageInfoMap[element] = info;
            computeCount++;
            if (computeCount == resultList.length) {
              loading(false);
              resultList.forEach((element) {
                selectList.add(SmartHomeUploadItemBean(
                  localUrl: element,
                  type: "01",
                  folderWidth: _imageInfoMap[element].image.width,
                  folderHeight: _imageInfoMap[element].image.height,
                ));
              });
              setState(() {
                _uploadList.addAll(selectList);
                if (_uploadList.length < 35) {
                  _allList.clear();
                  _allList.addAll(_uploadList);
                  _allList.add(_defaultItem);
                } else {
                  _allList.clear();
                  _allList.addAll(_uploadList);
                }
              });
              Future.delayed(Duration(milliseconds: 300), () {
                _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
              });
            }
          }));
    });

  }

}
